<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Corporates extends CI_Controller {
    /* PAGES */

    /**
     * Constructeur de la class Corporates.
     */
    public function __construct() {
        parent::__construct();

        $this->acl->setModule('corporates');
    }

    /**
     * Page d'administration des sociétés.
     */
    public function admin() {
        $this->acl->can('manage');

        $crud = new grocery_CRUD();

        $crud->set_table('S_BUSINESS_DATA.V_CORPORATE_CRP')
                ->set_subject('une société')

                // Champs.
                ->columns('CRP_NAME', 'CRP_ADDRESS', 'CRP_CITY', 'CRP_ZIPCODE', 'CRP_COUNTRY', 'CRP_PHONE', 'CRP_FAX', 'CRP_SIRET', 'CRP_APE', 'CRP_CAPITAL', 'CRP_TVA')
                ->fields('CRP_NAME', 'CRP_ADDRESS', 'CRP_CITY', 'CRP_ZIPCODE', 'CRP_COUNTRY', 'CRP_PHONE', 'CRP_FAX', 'CRP_SIRET', 'CRP_APE', 'CRP_CAPITAL', 'CRP_TVA')
                ->required_fields('CRP_NAME', 'CRP_ADDRESS', 'CRP_CITY', 'CRP_ZIPCODE', 'CRP_COUNTRY')

                // Affichage.
                ->display_as('CRP_ADDRESS', 'Adresse')
                ->display_as('CRP_APE', 'Code APE')
                ->display_as('CRP_CAPITAL', 'Capital')
                ->display_as('CRP_CITY', 'Ville')
                ->display_as('CRP_COUNTRY', 'Pays')
                ->display_as('CRP_FAX', 'Fax')
                ->display_as('CRP_NAME', 'Nom')
                ->display_as('CRP_PHONE', 'Téléphone')
                ->display_as('CRP_SIRET', 'Numéro de SIRET')
                ->display_as('CRP_TVA', 'Numéro de TVA')
                ->display_as('CRP_ZIPCODE', 'Code postal')

                //actions.
                ->add_action('Liens', img_url('corporates/clients.png'), 'corporates/adminCustomers')

        ;
        $crud->order_by('CRP_NAME', 'ASC');

        // Callbacks
        $crud->callback_delete(array($this, 'callbackCorporateDelete'));
        $crud->callback_insert(array($this, 'callbackCorporateInsert'));
        $crud->callback_update(array($this, 'callbackCorporateUpdate'));

        $this->db = $this->load->database('DB_PLASTPROD', true);
        $output = $crud->render();

        $css = $crud->get_css_files();
        $js = $crud->get_js_files();

        $this->layout
                ->setTitle('Sociétés')
                ->setCss($css)
                ->setJs($js)
                ->view('corporates/admin', $output)
                ->display()
        ;
    }

    /**
     * Gestion des "clients" d'une société
     * @param   int     $id
     */
    public function adminCustomers($id) {
        $this->acl->can('manage');

        $crud = new grocery_CRUD();

        $crud->set_table('S_BUSINESS_DATA.V_CUSTOMER_CUS')
                ->set_subject('une client')

                // Champs.
                ->columns('CVL_CIVILITY', 'USR_LAST_NAME', 'USR_FIRST_NAME', 'CUS_FUNCTION', 'USR_EMAIL', 'CUS_PHONE', 'CUS_FAX')
                ->add_fields('CRP_ID', 'CVL_ID', 'USR_LAST_NAME', 'USR_FIRST_NAME', 'CUS_FUNCTION', 'USR_EMAIL', 'CUS_PHONE', 'CUS_FAX', 'USR_LOGIN', 'USR_PASSWORD', 'PASS2', 'USR_EXTERNAL_ACCESS')
                ->edit_fields('CVL_ID', 'USR_LAST_NAME', 'USR_FIRST_NAME', 'CUS_FUNCTION', 'USR_EMAIL', 'CUS_PHONE', 'CUS_FAX', 'USR_LOGIN')
                ->required_fields('CRP_ID', 'CVL_ID', 'USR_LAST_NAME', 'USR_FIRST_NAME', 'CUS_FUNCTION', 'USR_EMAIL', 'CUS_PHONE', 'CUS_FAX', 'USR_LOGIN', 'USR_PASSWORD', 'PASS2', 'USR_EXTERNAL_ACCESS')

                // Affichage.
                ->display_as('CUS_FAX', 'Fax')
                ->display_as('CUS_FUNCTION', 'Fonction')
                ->display_as('CUS_PHONE', 'Téléphone')
                ->display_as('CVL_ID', 'Titre')
                ->display_as('CVL_CIVILITY', 'Titre')
                ->display_as('CVL_ID', 'Titre')
                ->display_as('PASS2', 'Resaisir mot de passe')
                ->display_as('USR_EMAIL', 'E-mail')
                ->display_as('USR_EXTERNAL_ACCESS', 'Accès externe')
                ->display_as('USR_FIRST_NAME', 'Prénom')
                ->display_as('USR_LAST_NAME', 'NOM')
                ->display_as('USR_LOGIN', 'Identifiant')
                ->display_as('USR_PASSWORD', 'Mot de passe')
                ->field_type('CRP_ID', 'hidden', $id)
        ;

        $crud->where('CRP_ID', $id);
        $crud->order_by('USR_LAST_NAME', 'ASC');

        if ('add' === $crud->getState() || 'edit' === $crud->getState()) {
            $crud->set_relation('CVL_ID', 'S_BUSINESS_DATA.T_P_CIVILITY_CVL', 'CVL_CIVILITY');
        }

        // Callbacks
        $crud->callback_delete(array($this, 'callbackCustomerDelete'));
        $crud->callback_insert(array($this, 'callbackCustomerInsert'));
        $crud->callback_update(array($this, 'callbackCustomerUpdate'));

        $this->db = $this->load->database('DB_PLASTPROD', true);
        $output = $crud->render();

        $css = $crud->get_css_files();
        $js = $crud->get_js_files();

        $this->layout
                ->setTitle('Clients')
                ->setCss($css)
                ->setJs($js)
                ->view('corporates/adminCustomers', $output)
                ->display()
        ;
    }

    /* CALLBACKS */

    /**
     * Callback de suppression d'un client.
     * 
     * @param   int     $id
     * @return  boolean
     */
    public function callbackCustomerDelete($id) {
        if ($this->acl->can('manage', false)) {
            // Récuperation de l'ID utilisateur.
            $this->db = $this->load->database('DB_PLASTPROD', true);
            $tmp = $this->db->query('SELECT "DB_PLASTPROD"."S_BUSINESS_DATA"."F_CUSTOMER_GET_USR_ID"(' . $id . ') AS "USR_ID"')->result();
            $usrId = $tmp[0]->USR_ID;

            $datas = array(
                $usrId
            );

            $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_D_USER_00', $datas);

            // Si la creation de l'utilisateur fonctionne.
            if ('SUCCESS' === $result->RESULT) {
                $datas = array(
                    $id
                );

                $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_D_CUSTOMER_00', $datas);

                if ('SUCCESS' === $result->RESULT)
                    return true;
            }
        }
        return false;
    }

    /**
     * Callback de création d'un client.
     * 
     * @param   array   $post
     * @return  boolean
     */
    public function callbackCustomerInsert($post) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $post['CVL_ID'],
                '\'' . pg_escape_string($post['USR_LOGIN']) . '\'',
                '\'' . pg_escape_string($post['USR_PASSWORD']) . '\'',
                '\'' . pg_escape_string($post['USR_FIRST_NAME']) . '\'',
                '\'' . pg_escape_string($post['USR_LAST_NAME']) . '\'',
                '\'' . pg_escape_string($post['USR_EMAIL']) . '\'',
                '\'' . $post['USR_EXTERNAL_ACCESS'] . '\'',
            );

            $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_I_USER_00', $datas);

            // Si la creation de l'utilisateur fonctionne.
            if ('SUCCESS' === $result->RESULT) {
                $datas = array(
                    $result->MESSAGE,
                    $post['CRP_ID'],
                    '\'' . pg_escape_string($post['CUS_FUNCTION']) . '\'',
                    '\'' . pg_escape_string($post['CUS_PHONE']) . '\'',
                    '\'' . pg_escape_string($post['CUS_FAX']) . '\''
                );

                $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_I_CUSTOMER_00', $datas);

                if ('SUCCESS' === $result->RESULT)
                    return true;
            }
        }
        return false;
    }

    /**
     * Callback de mise à jour d'un client.
     * 
     * @param   array   $post
     * @param   int     $id
     * @return  boolean
     */
    public function callbackCustomerUpdate($post, $id) {
        if ($this->acl->can('manage', false)) {
            // Récuperation de l'ID utilisateur.
            $this->db = $this->load->database('DB_PLASTPROD', true);
            $tmp = $this->db->query('SELECT "DB_PLASTPROD"."S_BUSINESS_DATA"."F_CUSTOMER_GET_USR_ID"(' . $id . ') AS "USR_ID"')->result();
            $usrId = $tmp[0]->USR_ID;

            $datas = array(
                $usrId,
                $post['CVL_ID'],
                '\'' . pg_escape_string($post['USR_LOGIN']) . '\'',
                '\'' . pg_escape_string($post['USR_FIRST_NAME']) . '\'',
                '\'' . pg_escape_string($post['USR_LAST_NAME']) . '\'',
                '\'' . pg_escape_string($post['USR_EMAIL']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_U_USER_00', $datas);

            // Si la creation de l'utilisateur fonctionne.
            if ('SUCCESS' === $result->RESULT) {
                $datas = array(
                    $id,
                    '\'' . pg_escape_string($post['CUS_FUNCTION']) . '\'',
                    '\'' . pg_escape_string($post['CUS_PHONE']) . '\'',
                    '\'' . pg_escape_string($post['CUS_FAX']) . '\''
                );

                $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_U_CUSTOMER_00', $datas);

                if ('SUCCESS' === $result->RESULT)
                    return true;
            }
        }
        return false;
    }

    /**
     * Callback de suppression d'une société.
     * 
     * @param   int     $id
     * @return  boolean
     */
    public function callbackCorporateDelete($id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id
            );

            $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_D_CORPORATE_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                return true;
        }
        return false;
    }

    /**
     * Callback de création d'une société.
     * 
     * @param   array   $post
     * @return  boolean
     */
    public function callbackCorporateInsert($post) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                '\'' . pg_escape_string($post['CRP_NAME']) . '\'',
                '\'' . pg_escape_string($post['CRP_ADDRESS']) . '\'',
                '\'' . pg_escape_string($post['CRP_CITY']) . '\'',
                '\'' . pg_escape_string($post['CRP_ZIPCODE']) . '\'',
                '\'' . pg_escape_string($post['CRP_COUNTRY']) . '\'',
                '\'' . pg_escape_string($post['CRP_PHONE']) . '\'',
                '\'' . pg_escape_string($post['CRP_FAX']) . '\'',
                '\'' . pg_escape_string($post['CRP_SIRET']) . '\'',
                '\'' . pg_escape_string($post['CRP_APE']) . '\'',
                '\'' . pg_escape_string($post['CRP_CAPITAL']) . '\'',
                '\'' . pg_escape_string($post['CRP_TVA']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_I_CORPORATE_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                return $result->MESSAGE;
        }
        return false;
    }

    /**
     * Callback de mise à jour d'une société.
     * 
     * @param   array   $post
     * @param   int     $id
     * @return  boolean
     */
    public function callbackCorporateUpdate($post, $id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id,
                '\'' . pg_escape_string($post['CRP_NAME']) . '\'',
                '\'' . pg_escape_string($post['CRP_ADDRESS']) . '\'',
                '\'' . pg_escape_string($post['CRP_CITY']) . '\'',
                '\'' . pg_escape_string($post['CRP_ZIPCODE']) . '\'',
                '\'' . pg_escape_string($post['CRP_COUNTRY']) . '\'',
                '\'' . pg_escape_string($post['CRP_PHONE']) . '\'',
                '\'' . pg_escape_string($post['CRP_FAX']) . '\'',
                '\'' . pg_escape_string($post['CRP_SIRET']) . '\'',
                '\'' . pg_escape_string($post['CRP_APE']) . '\'',
                '\'' . pg_escape_string($post['CRP_CAPITAL']) . '\'',
                '\'' . pg_escape_string($post['CRP_TVA']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_BUSINESS_DATA', 'P_U_CORPORATE_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                return true;
        }
        return false;
    }

}